<style scoped>
.query {
  background: #fff;
  border: 1px solid #e5ebec;
  color: #000;
}
.query-title {
  padding: 10px 15px;
  font-size: 16px;
  font-weight: bold;
  color: #333b47;
}
.query-footer {
  padding: 10px 30px;
  color: #2d8cf0;
}
.query-inner {
  border-top: 1px solid #e5ebec;
  border-bottom: 1px solid #e5ebec;
  color: #333b47;
  overflow: hidden;
  display: flex;
}
.query-inner-left {
  flex: 1;
  float: left;
  border-right: 1px solid #e5ebec;
  font-size: 14px;
}
.query-inner-right {
  flex: 2;
  float: left;
  font-size: 14px;
}
.select-studies {
  padding: 10px 15px;
  border-bottom: 1px solid #e5ebec;
}
.select-studies > div {
  float: right;
}
.selectStudies,
.selectStudiesname {
  height: 185px;
  overflow: hidden;
  overflow-y: scroll;
}
.Studiescheck {
  padding: 5px 15px;
}
.genemap {
  height: 180px;
  margin: 16px 0;
  border: 1px solid #e5ebec;
  background: #fff;
  overflow: hidden;
  box-sizing: border-box;
  position: relative;
}
.genemap-type {
  height: 20px;
  line-height: 20px;
  text-align: center;
}
.genemap-title {
  color:rgba(144,154,160,1);
  height: 20px;
  font-size: 16px;
  text-align: center;
}
.tip {
  display: none;
  position: absolute;
  opacity: 0.5;
  background: #000;
  color: #fff;
  border-radius: 5px;
  padding: 5px;
  font-size: 8px;
  z-index: 99;
}
.genedata {
  height: 380px;
  border: 1px solid #e5ebec;
  background: #fff;
  color: #333b47;
}
.genedata-table {
  width: 100%;
  height: 100%;
  padding: 15px 15px 35px;
  box-sizing: border-box;
}
.ivu-table-wrapper {
  height: 100%;
}
.genedata-table .ivu-table td {
  height: 40px;
}
.fontColor {
  color: #2d8cf0;
}

.layout-header-bar {
  background: #fff;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  color: #909aa0;
}
.layout-header-bar-left {
  float: left;
  width: 80%;
}
.layout-header-bar-left > div,
.layout-header-bar-right > div {
  float: left;
}
.layout-header-bar-right {
  float: right;
}
.portrait {
  width: 30px;
  height: 30px;
  border-radius: 50%;
  background: red;
  margin: 15px 0 0;
}
.layout-logo-left {
  width: 90%;
  height: 30px;
  background: #5b6270;
  border-radius: 3px;
  margin: 15px auto;
}
.ivu-layout-content {
  background: none !important;
}
.ivu-layout-header {
  padding: 0 30px;
}
</style>

<template>
  <Layout>
    <Header class="layout-header-bar">
      <div class="layout-header-bar-left">
        <div style="width:60%;margin-right:10px;">
          <Input
            v-model="geneName"
            suffix="ios-search"
            placeholder=" Serch...."
            @on-enter="searchEvent"
            @on-click="searchEvent" 
          />
        </div>
        <div style="margin:0 10px;">
          <Tooltip placement="top" max-width="400">
            <Icon type="md-help-circle" color="#2d8cf0" size="16"/>
            <div slot="content">
              <p>The input should be one or more genes, separated by comma.</p>
              <p>Each gene can be followed by a space and one or more mutations.</p>
              <p>Muations should be separated by slash.</p>
              <p>Please click the "try" button to see examples.</p>
            </div>
          </Tooltip>
        </div>
        <div style="margin-left:10px">
          Found
          <span style="color:#2d8cf0;">{{genedataTotal}}</span>
          mutations.
        </div>
      </div>
      <div class="layout-header-bar-right">
        <div class="portrait"></div>
        <div style="margin:0 10px;">admin
          <Icon type="md-arrow-dropdown"/>
        </div>
        <div>
          <Icon type="md-settings"/>
        </div>
      </div>
    </Header>
    <Content :style="{margin: '20px', background: '#fff'}">
      <div class="query">
        <div class="query-title">QUERY</div>
        <div class="query-inner">
          <div class="query-inner-left">
            <div class="select-studies">
              <span style="font-weight:bold;">Select Studies</span>
              <span>({{allcancerStudieslen}})</span>
              <div>
                <Checkbox
                  :value="cancercheckall"
                  @click.prevent.native="handleCheckAll('cancer')"
                >全选</Checkbox>
              </div>
            </div>
            <div class="selectStudies">
              <CheckboxGroup v-model="cancerStudies" @on-change="cancercheckAllGroupChange">
                <div v-for="(item,index) in allcancerStudies" :key="index" class="Studiescheck">
                  <Checkbox :label="index">{{item.name}}</Checkbox>
                  <span style="float:right;">{{item.count}}</span>
                </div>
              </CheckboxGroup>
            </div>
          </div>
          <div class="query-inner-right">
            <div class="select-studies">
              <span style="font-weight:bold;float:left;">STUDIES</span>
              <span>({{allselectStudieslen}})</span>
              <div>
                <Checkbox
                  :value="selectcheckall"
                  @click.prevent.native="handleCheckAll('select')"
                >全选</Checkbox>
              </div>
            </div>
            <div class="selectStudiesname">
              <div>
                <CheckboxGroup v-model="selectStudies" @on-change="selectcheckAllGroupChange">
                  <div v-for="(item,index) in allselectStudies" :key="index" class="Studiescheck">
                    <div>{{item.name}}</div>
                    <div v-for="(items,indexs) in item.study" :key="indexs">
                      <Checkbox :label="items.index">{{items.name}}</Checkbox>
                    </div>
                  </div>
                </CheckboxGroup>
              </div>
            </div>
          </div>
        </div>
        <div class="query-footer">{{studylen}} studies lelected</div>
      </div>
      <div class="genemap">
        <div class="genemap-type">
          <span style="color:black;">Mutation Types:</span>
          <span :style="{color:typeColor[0].color}">.slient</span>
          <span :style="{color:typeColor[1].color}">.missense</span>
          <span :style="{color:typeColor[2].color}">.inframe_indel</span>
          <span :style="{color:typeColor[3].color}">.frameshift</span>
          <span :style="{color:typeColor[4].color}">.nonsense</span>
        </div>
        <div class="genemap-title">
          {{picTitle.gene}}&nbsp;{{picTitle.transcript}}
        </div>
        <div class="tip" :style="tipClass" >
          <p v-for="(item,index) in tipMessage" :key="index">{{item.gene}}({{item.count}})</p>
        </div>
        <canvas id="myCanvas" @mousemove="moveOnCanvas" @mousedown="picClick"></canvas>
      </div>
      <div class="genedata">
        <div class="genedata-table">
          <Table
            border
            :columns="genedata_columns"
            :data="genedata"
            @on-sort-change="sortChange"
            height="315"
            :loading="loading"

          >
          <template slot-scope="{ row }" slot="freq">
              <span v-if='row.freq==0'>N/A</span>
              <span v-else>{{ row.freq }}</span>
            </template>
            <template slot-scope="{ row }" slot="cancer">
              <span v-if='row.cancer==""'>N/A</span>
              <span v-else>{{ row.cancer }}</span>
            </template>
            <template slot-scope="{ row }" slot="mutation">
              <span class="fontColor" @click="toMutation(row)">{{ row.mutation }}</span>
            </template>
            <template slot-scope="{ row }" slot="sample">
              <span class="fontColor" @click="sampleCheck(row)">{{ row.sample }}</span>
            </template>
            <template slot-scope="{ row }" slot="study">
              <span class="fontColor" @click="studyPopper(row)">{{row.studyName}}</span>
            </template>
          </Table>
          <div style="margin:12px 0;float:right;">
            <Page
              :total="genedataTotal"
              size="small"
              show-elevator
              show-total
              :page-size="20"
              @on-change="pageChange"
              :current="page"
            />
          </div>
        </div>
      </div>
    </Content>
  </Layout>
</template>
<script>
import { varca } from "@/api/index";
import bus from "@/base/eventbus";
import { Content, Header } from "iview";
export default {
  name: "variantlocus",
  data() {
    return {
      geneName: "", //ABI1
      page: 1,
      cancers: [],
      selectcheckall: false,
      selectStudies: [],
      cancercheckall: false,
      cancerStudies: [],
      findGene: {},
      allcancerStudies: [],
      allcancerStudieslen: 0,
      allselectStudieslen: 0,
      loading: false,
      allselectStudies: [],
      studylen: 0,
      genedataTotal: 0,
      genedata_columns: [
        {
          title: "Gene",
          key: "gene",
          sortable: "custom"
        },
        {
          title: "Mutation",
          slot: "mutation",
          sortable: "custom"
        },
        {
          title: "Freq",
          slot: "freq",
          sortable: "custom"
        },
        {
          title: "Sample",
          slot: "sample",
          sortable: "custom"
        },
        {
          title: "Cancer",
          slot: "cancer",
          sortable: "custom"
        },
        {
          title: "Study",
          slot: "study",
          sortable: "custom"
        }
      ],
      genedata: [],
      dataList:[],
      picture: {},
      typeColor: [
        {
          type: "slient",
          color: "rgb(0, 204, 102)"
        },
        {
          type: "missense",
          color: "rgb(0, 0, 255)"
        },
        {
          type: "inframe_indel",
          color: "rgb(153, 51, 255)"
        },
        {
          type: "frameshift",
          color: "rgb(255,102,0)"
        },
        {
          type: "nonsense",
          color: "rgb(255,0,0)"
        }
      ],
      xAxis: [],
      picTitle: {
        gene: "",
        transcript: ""
      },
      animateArr: [], //存柱状图数据 x坐标 y坐标 w宽度,h高度 xName 横坐标 detailData基因数量
      tipMessage: [],
      tipClass: {
        left: 0,
        top: 0,
        display: "none"
      }
    };
  },
  methods: {
    //查看mutation信息
    toMutation(row) {
      this.$store.state.mutationData = row;
      this.$router.push({ name: "variantlocusmutation" });
    },
    //查看样本信息
    sampleCheck(row) {
      this.$store.state.sampleInfo = row;
      this.$router.push({ name: "variantlocussample" });
    },
    getselectstudy() {
      let obj = {
        gene: this.geneName
      };
      varca.findSelectByGene(obj).then(res => {
        if (res.status == 200) {
          this.cancers = res.data.cancers;
          this.allcancerStudies = res.data.cancers;
          this.allcancerStudieslen = this.allcancerStudies.length;
        } else if (res.status == 203) {
          this.getselectstudy();
        }
      });
    },
    getgenedata() {
      this.genedataTotal = 0;
      this.genedata = [];
      this.loading = true;
      varca
        .findByGene(this.findGene)
        .then(res => {
          let newobj = {};
          newobj["allselectStudies"] = this.allselectStudies;
          newobj["selectStudies"] = this.selectStudies;
          newobj["allcancerStudies"] = this.allcancerStudies;
          newobj["cancerStudies"] = this.cancerStudies;
          newobj["selectcheckall"] = this.selectcheckall;
          newobj["cancercheckall"] = this.cancercheckall;
          newobj["findGene"] = this.findGene;
          newobj["cancers"] = this.cancers;
          this.$store.commit("updateMessage", newobj);
          if (res.status == 200) {
            if ("sname" in this.findGene || "cancer" in this.findGene) {
              this.genedataTotal = res.data.total;
              this.genedata = res.data.data;
            }
            this.loading = false;
          } else if (res.status == 203) {
            this.getgenedata();
          } else {
            this.loading = false;
          }
        })
        .catch(err => {});
    },
    //排序
    sortChange(column) {
      delete this.findGene["asc"];
      delete this.findGene["desc"];
      if (column.order != "normal") {
        if (column.key) {
          this.findGene[column.order] = column.key;
        } else {
          this.findGene[column.order] = column.column.slot;
        }
      }
      this.getgenedata();
    },
    //页码切换
    pageChange(index) {
      this.page = index;
      this.findGene["page"] = this.page;
      this.getgenedata();
    },
    //study详情
    studyPopper(row) {
      this.$store.state.studyId = row.studyId;
      this.$router.push("/VariantLocusStudy");
    },
    //全选
    handleCheckAll(handle) {
      this.genedata = [];
      if (handle == "select") {
        this.studylen = 0;
        this.selectStudies = [];
        this.selectcheckall = !this.selectcheckall;
        delete this.findGene["sname"];
        if (this.selectcheckall) {
          this.allselectStudies.forEach(item => {
            item.study.forEach(items => {
              this.selectStudies.push(items.index);
            });

            this.studylen += item.study.length;
          });
          this.findGene["sname"] = "all";
        }
      } else if (handle == "cancer") {
        this.cancercheckall = !this.cancercheckall;
        delete this.findGene["cancer"];
        delete this.findGene["sname"];
        this.allselectStudies = [];
        this.cancerStudies = [];
        this.allselectStudieslen = 0;
        this.selectStudies = [];
        this.studylen = 0;
        if (this.cancercheckall) {
          this.allcancerStudies.forEach(item => {
            this.cancerStudies.push(item.index);
          });
          this.allselectStudies = this.cancers;
          this.allselectStudies.forEach(item => {
            this.allselectStudieslen += item.study.length;
            item.study.forEach(items => {
              this.selectStudies.push(items.index);
            });
            this.studylen += item.study.length;
          });
          this.findGene["cancer"] = "all";
          this.findGene["sname"] = "all";
        }
        this.selectcheckall = this.cancercheckall;
      }
      if (this.selectcheckall) {
        this.getgenedata();
      }
    },
    //select study 选择
    selectcheckAllGroupChange(data) {
      delete this.findGene["sname"];
      this.studylen = 0;
      if (data.length > 0) {
        this.studylen = data.length;
        this.findGene["sname"] = data.join(",");
      }
      if ("sname" in this.findGene && "cancer" in this.findGene) {
        this.getgenedata();
      }
    },
    cancercheckAllGroupChange(data) {
      delete this.findGene["cancer"];
      this.allselectStudies = [];
      this.allselectStudieslen = 0;
      if (data.length > 0) {
        this.findGene["cancer"] = data.join(",");
        this.cancers.forEach(item => {
          if (data.indexOf(item.index) > -1) {
            this.allselectStudies.push(item);
            this.allselectStudieslen += item.study.length;
          }
        });
      }
    },
    searchEvent() {
      this.$store.state.geneName = this.geneName;
      this.page = 1;
      this.findGene = {
        gene: this.geneName,
        page: this.page
      };
      this.getselectstudy();
      this.getPictureInfo();
    },
    isEmptyObject(obj) {
      for (var key in obj) {
        return false;
      }
      return true;
    },
    getPictureInfo() {

      let cv = document.getElementById("myCanvas");
      let ctx=cv.getContext("2d");
      ctx.clearRect(50,0,1600,140)

      let obj = {
        gene:this.$store.state.geneName
      };
      varca
        .getPictureInfo(obj)
        .then(res => {
          if (res.status == 200) {
            this.dataList=res.data.data;
            this.picture = res.data.picture;
            this.xAxis = res.data.genes.exons;
            this.picTitle.gene = res.data.genes.gene;
            this.picTitle.transcript = res.data.genes.transcript;
            if(this.dataList.length!=0){  //有数据才画图
              this.drawPic();
            }          
          } else {
            this.$Message.error(res.msg);
          }
        })
        .catch(error => {
          this.$Message.error(error);
        });
    },
    drawPic() {
      let w = 1600,
        h = 140,
        bottomHeight = 30; //高度底部留30
      
      let cv = document.getElementById("myCanvas");
      cv.height = h;
      cv.width = w;
      let ctx = cv.getContext("2d");
      let count = this.xAxis[this.xAxis.length - 1]; //取this.xAxis中最大值
      let colWidth = (w - 100) / (count + 1); //左右各预留宽度50   计算每条的宽度 两个数之间的空白不计算  
     
      for (let i = 0; i <= count; i++) {
        //从0开始递增1至最大值
        //根据外层的键值循环 0 1 5 10
        let parentKey = i;
        let barHeight = 0;
        let rw = colWidth;
        let x = i * colWidth;

        let newObject = []; //将外层对象下的列表合并  即0-p.V981Ffs*88  0-p.S206F下的数组合并为新数据
        let countByGene = []; //统计每个基因的数量
        if (this.picture[parentKey]) {
          //如果当前位置有数据
          Object.keys(this.picture[parentKey]).forEach(childKey => {
            //0-p.V981Ffs*88  0-p.S206F
            newObject = newObject.concat(this.picture[parentKey][childKey]);
            countByGene.push({
              gene: childKey,
              count: this.picture[parentKey][childKey].length
            });
          });
        }
        this.animateArr.push({
          x: x + 50,
          y: h - bottomHeight - newObject.length,
          rw: rw,
          rh: newObject.length,
          xname: parentKey,
          detailData: countByGene
        });
        //按颜色分类 画每个柱状图
        if (newObject.length > 0) {
          for (let j = 0; j < this.typeColor.length; j++) {
            let countByColor = newObject.filter(
              item => item.mutationType == this.typeColor[j].type
            );
            let eachChildCount = countByColor.length; //数据太少高度太低，可扩大高度
            barHeight += eachChildCount;
            let rh = eachChildCount;
            let y = h - bottomHeight - barHeight;
            ctx.fillStyle = this.typeColor[j].color;
            ctx.fillRect(x + 50, y, rw, rh);
          }
        }

        //显示部分横坐标 取自this.xAxis
        let findXIndex = this.xAxis.findIndex(val => val == parentKey);
        if (findXIndex != -1) {
          ctx.fillRect(x + 50, h - bottomHeight, 0.5, 8); //画坐标对应的竖线
          ctx.font = "8px Arial";
          ctx.fillStyle = "black";
          ctx.fillText(parentKey, x + 45, h - 10); //横坐标值

          //横坐标分段值
          ctx.font = "10px Arial";
          ctx.fillStyle = "#AA812C";
          let middleX = 0;
          if (findXIndex == 0) {
            middleX = this.xAxis[findXIndex] / 2 * colWidth;
          } else {
            middleX =
              (this.xAxis[findXIndex] + this.xAxis[findXIndex - 1]) /
              2 *
              colWidth;
          }
          ctx.fillText(findXIndex + 1, middleX + 45, h - 10);
        }
      }
    },
    moveOnCanvas(e) {
      let w = 1600,
        h = 400;
      let cv = document.getElementById("myCanvas");
      let ctx = cv.getContext("2d");

      let box = cv.getBoundingClientRect();
      let pos = {
        x: e.clientX - box.left,
        y: e.clientY - box.top
      };

      for (var i = 0, item, len = this.animateArr.length; i < len; i++) {
        item = this.animateArr[i];
        //鼠标移动显示提示信息
        ctx.save(); //保存当前环境状态
        ctx.beginPath();
        ctx.rect(item.x, item.y, item.rw, item.rh); //创建总高度矩形，用来判断鼠标是否在矩形内
        if (ctx.isPointInPath(pos.x, pos.y)) {
          cv.style.cursor = "pointer";
          this.showInfo(pos, item.detailData, true);
          ctx.restore(); //返回之前保存过的路径状态和属性
          break;
        }
        this.showInfo(pos, item.detailData, false);
        cv.style.cursor = "default";
        ctx.restore();
      }
    },
    showInfo(pos, obj, isShow) {
      this.tipMessage = [];
      if (isShow) {
        this.tipMessage = obj;
        this.tipClass.left = pos.x+5 + "px";
        this.tipClass.top = pos.y + "px";
        this.tipClass.display = "block";
      } else {
        this.tipClass.display = "none";
      }
    },
    picClick(e){
      let cv = document.getElementById("myCanvas");
      let ctx = cv.getContext("2d");

      let box = cv.getBoundingClientRect();
      console.log("点击图表位置",e.clientX - box.left)
    }
  },
  mounted() {
    if (this.$store.state.geneName) {
      this.geneName = this.$store.state.geneName;
      if (this.$store.state.allselectStudies.length > 0) {
        this.allselectStudies = this.$store.state.allselectStudies;
      }
      if (this.$store.state.selectStudies.length > 0) {
        this.selectStudies = this.$store.state.selectStudies;
        this.studylen = this.selectStudies.length;
      }
      if (this.$store.state.allcancerStudies.length > 0) {
        this.allcancerStudies = this.$store.state.allcancerStudies;
      }
      if (this.$store.state.cancerStudies.length > 0) {
        this.cancerStudies = this.$store.state.cancerStudies;
      }
      if (this.$store.state.cancers.length > 0) {
        this.cancers = this.$store.state.cancers;
      }

      this.selectcheckall = this.$store.state.selectcheckall;
      this.cancercheckall = this.$store.state.cancercheckall;
      this.findGene = this.$store.state.findGene;

      this.allselectStudieslen = this.allselectStudies.length;
      this.allcancerStudieslen = this.allcancerStudies.length;

      if (this.isEmptyObject(this.findGene) == false) {
        this.getgenedata();
      }
    }
  },
  watch: {
    geneName(val) {
      if (val != this.$store.state.geneName) {
        this.allselectStudies = [];
        this.selectStudies = [];
        this.allcancerStudies = [];
        this.cancerStudies = [];
        this.cancers = [];
        this.selectcheckall = false;
        this.cancercheckall = false;
        this.findGene = {};
        this.allselectStudieslen = 0;
        this.allcancerStudieslen = 0;
        this.genedata = [];
        this.genedataTotal = 0;
        this.$store.state.geneName = "";
        this.studylen = 0;
        let newobj = {};
        newobj["allselectStudies"] = this.allselectStudies;
        newobj["selectStudies"] = this.selectStudies;
        newobj["allcancerStudies"] = this.allcancerStudies;
        newobj["cancerStudies"] = this.cancerStudies;
        newobj["selectcheckall"] = this.selectcheckall;
        newobj["cancercheckall"] = this.cancercheckall;
        newobj["findGene"] = this.findGene;
        newobj["cancers"] = this.cancers;
        this.$store.commit("updateMessage", newobj);
      }
    }
  },
  components: {
    Content,
    Header
  }
};
</script>

